<template>
  <PageWrapper dense fixedHeight style="background-color: #fff">
    <div style="background-color: #fff; overflow: hidden">
      <a-alert
        message="请先选择数据通道,才能显示出指定通道的数据分类。"
        type="info"
        show-icon
        style="margin: 10px; padding: 5px"
      />
      <div style="display: flex">
        <BasicTable
          @register="registerTable"
          style="margin-bottom: 20px"
          :rowSelection="rowSelection"
          class="w-2/4 xl:w-2/4"
          :pagination="false"
        >
          <template #comtype="{ record }">
            {{ returnComtypeType(record) }}
          </template>
          <!-- 数据交换方向 -->
          <template #direction="{ record }">
            {{
              record.direction == 0
                ? '未定义'
                : record.direction == 1
                ? '向外'
                : record.direction == 2
                ? '向内'
                : '向外、向内'
            }}
          </template>

          <template #toolbar>
            <a-button type="primary" @click="onAddChannelButtonClick">新增通道</a-button>
          </template>
          <template #action="{ column, record }">
            <TableAction
              :actions="[
                {
                  icon: 'clarity:note-edit-line',
                  tooltip: '编辑',
                  onClick: onEditChannelButtonClick.bind(null, record),
                },
                {
                  icon: 'ant-design:delete-outlined',
                  color: 'error',
                  tooltip: '删除',
                  popConfirm: {
                    title: '是否确认删除',
                    placement: 'left',
                    confirm: onDeleteChannelButtonClick.bind(null, record),
                  },
                },
              ]"
            />
          </template>
        </BasicTable>
        <CategoryIndex :searchInfo="searchInfo" @success="onOkButtonClick" class="w-2/4 xl:w-2/4" />
      </div>
    </div>

    <AddOrUpdateChannel @register="registerAddOrUpdateChannelForm" @success="afterSuccess" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, reactive, ref, onBeforeMount, computed, unref } from 'vue';
  import { channelTableColumns } from './exchangeChannel.data';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { useModal } from '/@/components/Modal';
  import { queryEnumOption } from '/@/api/qms/exchangeData';
  import { queryAllChannel, deleteChannel } from '/@/api/qms/exchangeChannel';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import AddOrUpdateChannel from './component/AddOrUpdateChannel.vue';
  import { ExchangeChannelDto } from '/@/api/qms/model/exchangeChannelModel';
  import { EnumDto, EnumList } from '/@/api/qms/model/exchangeDataModel';
  import CategoryIndex from './CategoryIndex.vue';

  export default defineComponent({
    name: 'ChannelIndex',
    components: {
      BasicTable,
      PageWrapper,
      AddOrUpdateChannel,
      TableAction,
      CategoryIndex,
    },
    setup() {
      const searchInfo = reactive<Recordable>({});
      const comtypeEnum = ref<EnumList>([]);
      const [registerAddOrUpdateChannelForm, { openModal: openAddOrUpdateForm }] = useModal();
      const [registerTable, { reload }] = useTable({
        title: '数据交换通道',
        api: queryAllChannel,
        clickToRowSelect: true,
        rowKey: 'id',
        columns: channelTableColumns,
        // formConfig: {
        //     labelWidth: 80,
        //     schemas: paramConditionFormSchema,
        //     autoSubmitOnEnter: true,
        //     showResetButton: false,//查询条件部分中是否显示重置按钮
        // },
        ellipsis: false,
        canResize: true,
        // useSearchForm: true,
        immediate: true,
        bordered: true,
        striped: false,
        indexColumnProps: {
          width: 0,
        },
        actionColumn: {
          width: 80,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });
      const selectedRowKeys = ref<Number[]>([]);
      const rowSelection = computed(() => {
        return {
          selectedRowKeys: unref(selectedRowKeys),
          type: 'radio',
          columnWidth: 0,
          onChange: (key) => {
            if (key.length < 1) searchInfo.id = null;
            searchInfo.id = key[0];
            selectedRowKeys.value = key;
          },
        };
      });
      /**
       * 打开新增窗口,将左侧选中的分组传过去
       */
      function onAddChannelButtonClick() {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '数据通道管理',
          operateType: OperationTypeEnum.ADD,
        };
        openAddOrUpdateForm(true, propsData);
      }
      /**
       * 打开编辑窗口
       * @param record
       */
      function onEditChannelButtonClick(record: ExchangeChannelDto) {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '数据通道管理',
          operateType: OperationTypeEnum.EDIT,
          dataId: record.id,
        };
        openAddOrUpdateForm(true, propsData);
      }

      /**
       * 删除参数项
       * @param record
       */
      function onDeleteChannelButtonClick(record: ExchangeChannelDto) {
        deleteChannel(record.id)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              reload();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }
      function returnComtypeType(record: ExchangeChannelDto) {
        for (let i of comtypeEnum.value) {
          if (record.comtype === i.value) {
            return i.label;
          }
        }
        return record.comtype;
      }
      function onOkButtonClick(channelId: Number) {
        searchInfo.id = channelId;
        selectedRowKeys.value = [channelId];
        console.log(channelId, '传给父组件的channelId');
      }
      /**
       * 新增/编辑弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        reload();
      }
      onBeforeMount(() => {
        queryEnumOption('CommunicationChannelTypeEnum').then((res: EnumDto) => {
          let Options = [];
          for (let d of res[0].options) {
            // 这里要转number类型,因为获取全部参数类型请求回来的数据key为string,而其他接口为Number
            Options.push({ value: Number(d.key), label: d.value ? d.value : d.key });
          }
          comtypeEnum.value = Options;
        });
      });
      return {
        registerTable,
        registerAddOrUpdateChannelForm,
        searchInfo,
        comtypeEnum,
        returnComtypeType,
        onOkButtonClick,
        rowSelection,
        selectedRowKeys,
        afterSuccess,
        onAddChannelButtonClick,
        onEditChannelButtonClick,
        onDeleteChannelButtonClick,
      };
    },
  });
</script>
